package com.voicechat.firstmet.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mabeijianxi.jianxiexpression.widget.ExpressionEditText;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.MsgGifGridViewAdapter;
import com.voicechat.firstmet.adapter.PostDetailsAdapter;
import com.voicechat.firstmet.adapter.ViewPagerAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CommentBean;
import com.voicechat.firstmet.bean.GifBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.fragment.EmojiShowFragment;
import com.voicechat.firstmet.fragment.IMSendGifFragment;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.net.service.PersonDataService;
import com.voicechat.firstmet.realm.ListBean;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.RealmUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.ScreenUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CirclePageIndicator;
import com.voicechat.firstmet.view.Control;
import com.voicechat.firstmet.view.EmojiKeyboard;
import com.voicechat.firstmet.view.EmotionInputDetector;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: PostDetailsActivity
 * @Description: 帖子详情
 * @Author: ljp
 * @CreateDate: 2018/9/11 19:25
 * @Version: 1.0
 */
public class PostDetailsActivity extends BaseActivity implements UMShareListener {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.recycler_comment)
    RecyclerView recyclerComment;
    @BindView(R.id.et_comment_content)
    ExpressionEditText etCommentContent;
    @BindView(R.id.image_like)
    ImageView imageLike;
    @BindView(R.id.tv_like_num)
    TextView tvLikeNum;
    @BindView(R.id.image_enjoy)
    ImageView imageEnjoy;
    @BindView(R.id.image_share)
    ImageView imageShare;
    @BindView(R.id.fl_emogi)
    FrameLayout flEmogi;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.linear_content)
    LinearLayout linearContent;
    @BindView(R.id.linear_llo)
    LinearLayout linearLlo;
    @BindView(R.id.linear_zan)
    LinearLayout linearZan;
    @BindView(R.id.tv_send)
    TextView tvSend;

    /* @BindView(R.id.fl_emotionview_main)
     FrameLayout flEmotionviewMain;*/
    // private ExpressionShowFragment expressionShowFragment;
    private ArrayList<CommentBean.PageBean.ListBean> commentBeans;
    private PostDetailsAdapter postDetailsAdapter;
    private boolean isEmogiShow;
    private boolean keyboardShown;
    private int supportSoftInputHeight;
    private String TAG = "PostDetailsActivity";
    private boolean isFirst = true;
    private EmojiKeyboard emojiKeyboard;
    private EmojiShowFragment emojiShowFragment;
    private EmotionInputDetector mDetector;
    private PostBean.PageBean.ListBean listBean;
    private PostBean.ObjectBean objectBean;
    CommentBean.PageBean.ListBean commentBean;//一级评论数据
    private boolean isMe;
    public static MySelfInfoBean.ObjectBean mySeleInfo;
    private String userId;
    private String token;
    int page = 1;
    private String deviceInfo;
    private Control mControl;
    private List<GifBean.PageBean.ListBean> gifBeans;
    private IMSendGifFragment sendGifFragment;
    private AnimationDrawable frameAnimatio;
    private MediaUtil mediaUtil;
    private Handler handler;


    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_post_detail;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        listBean = getIntent().getParcelableExtra("listBean");
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
       /* setRootOnTouchListener();
        setListenerToRootView();*/
        initKeyBoard(savedInstanceState);
        initHttpComment();
        setHomeGif();
    }
    /**
     * @return
     * @method
     * @description 一级评论数据
     * @date: 2018/11/1 14:12
     * @author: ljp
     */
    private void initHttpComment() {
        CommunityService.postComment(token, deviceInfo, listBean.getId(), userId, page + "").subscribe(commentBean -> {
            if (commentBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = commentBean.getPage().getCount() / commentBean.getPage().getPageSize() +
                        (commentBean.getPage().getCount() % commentBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (page > i) {//判断是否是最后一页{//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        commentBeans.clear();
                        smartRefresh.finishRefresh();
                    }
                    if(commentBean.getPage().getList() != null) {
                        commentBeans.addAll(commentBean.getPage().getList());
                        postDetailsAdapter.notifyDataSetChanged();
                    }
                    smartRefresh.finishLoadMore();
                }
            }else if(commentBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(commentBean.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }
    /**
     * @return
     * @method
     * @description 请求礼物信息
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void setHomeGif() {
        PersonDataService.showPersonGif(token, deviceInfo,listBean.getId(),PersonDataService.GIF_TYPE.GIF_PLAY,page+"").subscribe(gifBean -> {
           // Log.i(TAG, "setHomeHeard: ----" + gifBean.getPage().getList().size());
            if (gifBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    //gifBeans.clear();
                if(gifBean.getPage().getList() != null) {
                    gifBeans.addAll(gifBean.getPage().getList());
                    postDetailsAdapter.setGifBeans(gifBeans);
                    postDetailsAdapter.notifyDataSetChanged();
                }
            } else if(gifBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(gifBean.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }
    private void initKeyBoard(Bundle savedInstanceState) {
        if (emojiShowFragment == null) {
            emojiShowFragment = EmojiShowFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_emogi, EmojiShowFragment.newInstance()).commit();
        }
        emojiKeyboard = new EmojiKeyboard(this, etCommentContent, flEmogi, imageEnjoy, linearContent);
        emojiKeyboard.setEmoticonPanelVisibilityChangeListener(new EmojiKeyboard.OnEmojiPanelVisibilityChangeListener() {
            @Override
            public void onShowEmojiPanel() {
                Log.e(TAG, "onShowEmojiPanel");
            }

            @Override
            public void onHideEmojiPanel() {
                Log.e(TAG, "onHideEmojiPanel");
            }
        });
       /* mDetector = EmotionInputDetector.with(this)
               // .bindSendButton(mSendButton)
                .bindToEditText(null,etCommentContent)
                .setEmotionView(flEmogi)
                .bindToContent(recyclerComment)
                .bindToEmotionButton(imageEnjoy);*/
    }


    /**
     * @return
     * @method
     * @description 点击editText
     * @date: 2018/11/2 15:22
     * @author: ljp
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = View.inflate(context, R.layout.input_edit_comment, null);
            if (Utils.isShouldHideInputView(v, ev)) {
                //Utils.hideSoftInput(v.getWindowToken(), this);
                hideKeyboard(activity);
                etCommentContent.setHint("快评论吧");
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    /**
    * @method
    * @description 控件数据实例化
    * @date: 2018/11/7 19:44
    * @author: ljp
    * @return
    */
    private void initView() {
        EmojiShowFragment.setEditMsg(etCommentContent);
        gifBeans = new ArrayList<>();
        //Log.i(TAG, "initView: ------"+listBean.toString());
        if (listBean.getWarrant().equals("2")) { // 授权评论 1默认 2不允许评论
            etCommentContent.setFocusable(false);
            etCommentContent.setClickable(false);
        }
        recyclerComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Utils.hideSoftInput(v.getWindowToken(),context);
                        flEmogi.setVisibility(View.GONE);
                        hideKeyboard(activity);
                        etCommentContent.setHint("快评论吧");
                        //etCommentContent.setFocusable(false);
                        /*linearZan.setVisibility(View.VISIBLE);
                        imageShare.setVisibility(View.VISIBLE);
                        tvSend.setVisibility(View.GONE);*/
                        break;
                }
                return false;
            }
        });
        etCommentContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    linearZan.setVisibility(View.GONE);
                    imageShare.setVisibility(View.GONE);
                    tvSend.setVisibility(View.VISIBLE);
                }else {
                    linearZan.setVisibility(View.VISIBLE);
                    imageShare.setVisibility(View.VISIBLE);
                    tvSend.setVisibility(View.GONE);
                }

            }
        });
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*隐藏软键盘*/
                hideKeyboard(activity);
                    initHttpCommentData();//评论请求
            }
        });
        //判断是否是自己
        if (userId.equals(listBean.getUserId())) {
            isMe = true;
        } else {
            isMe = false;
        }
        tvLikeNum.setText(listBean.getFabulousCount() + "");
        if (listBean.getIsFabulous().equals("1")) {//我是否点赞  0 未点赞  1 已经点赞
            imageLike.setImageResource(R.mipmap.post_detail_like);
        } else {
            imageLike.setImageResource(R.mipmap.post_detail_unlike);
        }
        //点赞，取消赞
        imageLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("0")) {// 1 已经点赞   0 未点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                            tvLikeNum.setText(listBean.getFabulousCount() + "");
                            imageLike.setImageResource(R.mipmap.post_detail_like);
                        } else if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                            imageLike.setImageResource(R.mipmap.post_detail_unlike);
                            tvLikeNum.setText(listBean.getFabulousCount() + "");
                        }
                    } else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    }else {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    toast_MakeText(getResources().getString(R.string.net_error));
                    Log.i(TAG, "setLikeClick: -------" + throwable.toString());
                });
            }
        });
        etCommentContent.setHorizontallyScrolling(false);
        etCommentContent.setMaxLines(Integer.MAX_VALUE);
        commentBeans = new ArrayList<>();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                gifBeans.clear();
                initHttpComment();
                setHomeGif();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initHttpComment();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        postDetailsAdapter = new PostDetailsAdapter(context, commentBeans, R.layout.item_post_comment, listBean, isMe);
        postDetailsAdapter.addHeaderView(R.layout.item_head_post_comment);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        //linearLayoutManager.setReverseLayout(true);
        // linearLayoutManager.setStackFromEnd(true);
        recyclerComment.setLayoutManager(linearLayoutManager);
        recyclerComment.setAdapter(postDetailsAdapter);
        etCommentContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“GO”键*/
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    /*隐藏软键盘*/
                    hideKeyboard(activity);
                        initHttpCommentData();//评论请求
                    return true;
                }
                return false;
            }
        });
        //二级评论点击查看
        postDetailsAdapter.setItemClick(new PostDetailsAdapter.ItemClick() {
            //查看二级评论点击
            @Override
            public void setLinearComment(CommentBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(activity, CommentDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);
            }

            //点赞
            @Override
            public void setLikeClick(ImageView imageView, CommentBean.PageBean.ListBean listBean, TextView tvLiks) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, userId).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("0")) {// 1 已经点赞   0 未点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                            tvLiks.setText(listBean.getFabulousCount() + "");
                            imageView.setImageResource(R.mipmap.post_detail_like);
                        } else if (!TextUtils.isEmpty(listBean.getIsFabulous()) && listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                            imageView.setImageResource(R.mipmap.post_detail_unlike);
                            tvLiks.setText(listBean.getFabulousCount() + "");
                        }
                    } else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        removeAllActivity();
                        startActivity(new Intent(activity,LoginActivity.class));
                    }else {
                        toast_MakeText(result.getMsg());
                    }
                }, throwable -> {
                    toast_MakeText(getResources().getString(R.string.net_error));
                    //Log.i(TAG, "setLikeClick: -------" + throwable.toString());
                });
            }

            //点击跳往二级评论
            @Override
            public void setCommentClick(View view, CommentBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(activity, CommentDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);
            }
            //关注
            @Override
            public void setFansClick(View view, PostBean.PageBean.ListBean listBean) {
                setHttpLike(listBean);
            }
            //查看打赏礼物
            @Override
            public void setGifClick(View view, String postId) {
                Intent intent = new Intent(activity,GifListActivity.class);
                intent.putExtra("objectId",postId);
                startActivity(intent);
            }
            //打赏
            @Override
            public void setReward(View view) {
                //弹出打赏礼物页面
                setPopuGift();
            }
            /**
            * @method initView
            * @description 播放语音
            * @date: 2018/11/27 17:52
            * @author: ljp
            * @return void
            */
            @Override
            public void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, ImageView view) {
                String path = ConstantSet.VOICEINTR + ConstantSet.VOICE_POST + Utils.getVoiceName(listBean.getVoiceUrl());
                if (FileUtils.isExists(path)) {
                    try {
                        view.setImageResource(0);
                        view.setBackgroundResource(R.drawable.post_voice);
                        frameAnimatio = (AnimationDrawable) view.getBackground();
                        player(path,view);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void setIcon(PostBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(activity, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", listBean.getUserId());
                startActivity(intent);
            }
            @Override
            public void setIcon(CommentBean.PageBean.ListBean commentBean) {
            }
        });
    }
    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player(String filePath,ImageView imageView) throws FileNotFoundException {
        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        if (mediaUtil == null) {
            mediaUtil = MediaUtil.getInstance();
            mediaUtil.play(new FileInputStream(filePath));
            frameAnimatio.start();
        } else {
            if (mediaUtil.setPlayer()) {
                mediaUtil.stop();
                frameAnimatio.stop();
                imageView.setBackgroundResource(0);
                imageView.setImageResource(R.mipmap.send_post_voice_icon3);
            } else {
                mediaUtil.play(new FileInputStream(filePath));
                imageView.setImageResource(0);
                imageView.setBackgroundResource(R.drawable.post_voice);
                frameAnimatio = (AnimationDrawable) imageView.getBackground();
                frameAnimatio.start();
            }
        }
        mediaUtil.setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
                frameAnimatio.stop();
                imageView.setBackgroundResource(0);
                imageView.setImageResource(R.mipmap.send_post_voice_icon3);
            }
        });
    }
    /**
    * @method
    * @description 弹出打赏页面
    * @date: 2018/11/19 19:51
    * @author: ljp
    * @return
    */
    ViewPager viewPagerGif;
    TextView tvGoldSum;
    LinearLayout linearRecharge;
    TextView tvSendGift;
    ImageView imageClose;
    CirclePageIndicator llPointGroup;
    public static int gridColumn = 4;//grid的列数
    public static int gridNum = 8;//grid的一页总数
    private ViewPagerAdapter mAdapter;
    private List<GridView> gridViews;
    ListBean giftBean;//选中的礼物
    private void setPopuGift() {
        flEmogi.setVisibility(View.GONE);
        hideKeyboard(activity);
        View view = View.inflate(context, R.layout.popu_gift_fragment, null);
        tvSendGift = view.findViewById(R.id.tv_send);
        linearRecharge = view.findViewById(R.id.linear_recharge);
        tvGoldSum = view.findViewById(R.id.tv_gold_sum);
        viewPagerGif = view.findViewById(R.id.view_pager_gif);
        llPointGroup = view.findViewById(R.id.ll_point_group);
        imageClose = view.findViewById(R.id.image_close);
        Log.i(TAG, "setPopuGift: -----"+Utils.checkDeviceHasNavigationBar(activity));
        if(Utils.isHUAWEI()){
            if(Utils.checkDeviceHasNavigationBar(activity)){
                //Utils.hideBottomUIMenu(activity);
            }
        }
        initPopuView();
        initDatas();
        initHttpGetGold();
        //PopUtils.showPopupWindow(activity, view, false);
        PopUtils.initPopupWindow(activity, view, false);
        PopUtils.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = activity.getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                activity.getWindow().setAttributes(params);
                giftBean = null;
            }
        });
        imageClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
            }
        });
        tvSendGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: -------------------");
                if(giftBean != null){
                    MeInfoService.sendGift(userId,token,deviceInfo,listBean.getUserId(),giftBean.getId(),
                            giftBean.getGold()+"",PersonDataService.GIF_TYPE.GIF_PLAY,listBean.getId(),"1","post").subscribe(result -> {
                        Log.i(TAG, "onClick: ------"+result.toString());
                        if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                            toast_MakeText("打赏成功！");
                            gifBeans.clear();
                            page = 1;
                            setHomeGif();
                            PopUtils.hidePopupWindow();
                        }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                            Utils.setToken(context);
                        }else {
                            toast_MakeText(result.getMsg());
                        }
                    },throwable -> {
                        Log.i(TAG, "onClick: -----"+throwable.toString());

                    });
                }else {
                    toast_MakeText("请选择礼物");
                }

            }
        });
        linearRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
              /*  Uri uri = Uri.parse(HTTPAPI.URL_RECHARGE+"id="+mySeleInfo.getNumber());
                Log.i(TAG, "onClick: --------"+uri.toString());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);*/
                Intent intent = new Intent(activity, GoldDepositsActivity.class);
                intent.putExtra("diamondSum",Integer.parseInt(tvGoldSum.getText().toString()));
                startActivity(intent);
            }
        });
    }
    /**
     * @method
     * @description 余额请求
     * @date: 2018/11/7 14:39
     * @author: ljp
     * @return
     */
    private void initHttpGetGold() {
        MeInfoService.goldDiamond(userId,token,deviceInfo).subscribe(goldBean -> {
            //Log.i(TAG, "initHttp: -------"+goldBean.getObject().toString());
            if(goldBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                tvGoldSum.setText(goldBean.getObject().getGold()+"");
            }else if(goldBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(goldBean.getMsg());
            }
        },throwable -> {
            Log.i(TAG, "initHttp: -----"+throwable.toString());
        });

    }

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2018/11/13 10:07
     * @author: ljp
     */
    List<ListBean> listBeans;
    private void initPopuView() {
        gridViews = new ArrayList<>();
        listBeans = new ArrayList<>();
        listBeans.addAll(RealmUtils.getInstance()
                .getRealm()
                .where(ListBean.class)
                .findAll());
        Log.i(TAG, "initPopuView: ----"+listBeans.size());
        mAdapter = new ViewPagerAdapter();
        viewPagerGif.setAdapter(mAdapter);
        llPointGroup.setVisibility(View.VISIBLE);
        llPointGroup.setViewPager(viewPagerGif);

    }
    /**
    * @method
    * @description 礼物数据实例化
    * @date: 2018/11/20 11:23
    * @author: ljp
    * @return
    */
    private void initDatas() {
        //计算viewpager一共显示几页
        int pageSize = listBeans.size() % gridNum == 0
                ? listBeans.size() / gridNum
                : listBeans.size() / gridNum + 1;
        for (int i = 0; i < pageSize; i++) {
            GridView gridView = new GridView(activity);
            MsgGifGridViewAdapter adapter = new MsgGifGridViewAdapter(listBeans, i);
            gridView.setNumColumns(gridColumn);
            gridView.setHorizontalSpacing(5);
            gridView.setVerticalSpacing(10);
            gridView.setAdapter(adapter);
            int finalI = i;
            adapter.setItemClick(new MsgGifGridViewAdapter.ItemClick() {
                @Override
                public void setItemClick(int position) {

                }
            });
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    adapter.setCheckd(true,position);
                    adapter.notifyDataSetChanged();
                    giftBean = adapter.getItem(position);
                    //toast_MakeText(adapter.getItem(position)+"");
                }
            });
            gridViews.add(gridView);
        }
        mAdapter.add(gridViews);
    }

    /**
     * @method
     * @description 关注取消关注
     * @date: 2018/10/24 11:56
     * @author: ljp
     * @return
     */
    private void setHttpLike(PostBean.PageBean.ListBean listBean){
        MeInfoService.likeAndUnLike(token,deviceInfo,mySeleInfo.getId(),listBean.getUserId()).subscribe(result -> {
            Log.i(TAG, "setHttpLike: --------"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                if(listBean.getIsFollow().equals("1")){// 关注状态  1关注 0未关注
                    listBean.setIsFollow("0");
                }else if(listBean.getIsFollow().equals("0")){
                    listBean.setIsFollow("1");
                }
                postDetailsAdapter.notifyDataSetChanged();
                //toast_MakeText(result.getMsg());
            }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(result.getMsg());
            }
        },throwable -> {
            Log.i(TAG, "setHttpLike: ------"+throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }
    /**
     * @return
     * @method
     * @description 评论请求
     * @date: 2018/11/2 14:20
     * @author: ljp
     */
    private void initHttpCommentData() {
        String content = etCommentContent.getText().toString().trim();
        if (!TextUtils.isEmpty(content)) {
            CommunityService.submitPostComment(token, deviceInfo, listBean.getId(), userId, content).subscribe(result -> {
                Log.i(TAG, "initHttpCommentData: -------" + result.toString());
                if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    page = 1;
                    initHttpComment();
                    etCommentContent.setText("");
                    if(isKeyboardShown(etCommentContent)){
                        hideKeyboard(activity);
                    }else if(flEmogi.getVisibility() == View.VISIBLE) {
                        flEmogi.setVisibility(View.GONE);
                    }
                }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    Utils.setToken(context);
                }else {
                    toast_MakeText(result.getMsg());
                }
            }, throwable -> {
                Log.i(TAG, "initHttpCommentData: -------" + throwable.toString());

            });
        }else {
            toast_MakeText("请输入评论内容");
        }

    }

    @OnClick({R.id.linear_back, R.id.et_comment_content, R.id.image_like, R.id.image_enjoy, R.id.image_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.et_comment_content:
                // isEmogiShow = false;
                //Utils.showKeyboard(activity_imessage);
                break;
            case R.id.image_like:
                break;
            case R.id.image_enjoy:
                /*etCommentContent.setFocusable(true);
                etCommentContent.setFocusableInTouchMode(true);
                etCommentContent.requestFocus();//获取焦点 光标出现*/
                //showKeyboard(activity,etCommentContent);
                //flEmogi.setVisibility(View.VISIBLE);
                  /*  handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showSoftKeyboard(true);
                        }
                    }, 200);*/
                break;
            case R.id.image_share://分享
               /* String[] strings = new String[9];
                if(!TextUtils.isEmpty(listBean.getUrl())){
                   strings = Utils.spitPictureUrl(listBean.getUrl());
                   // uri = Uri.parse(OssConfig.OSS_HTTP+strings[0]);
                }
                UMWeb web = new UMWeb("https://www.baidu.com/");
                web.setTitle(listBean.getMdTitle());//标题
                web.setThumb(new UMImage(activity, OssConfig.OSS_HTTP+strings[0]));  //缩略图
                web.setDescription(listBean.getContent());//描述
                new ShareAction(activity).withMedia(web)
                        .setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE)
                        .setCallback(this).open();*/
                break;
        }
    }
    private InputMethodManager inputMethodManager;
    /**
     * 令编辑框获取焦点并显示键盘
     */
    private void showSoftKeyboard(boolean saveSoftKeyboardHeight) {
        etCommentContent.requestFocus();
        inputMethodManager = (InputMethodManager) this.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(etCommentContent, 0);
        if (saveSoftKeyboardHeight) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getSoftKeyboardHeight();
                }
            }, 200);
        }
    }
    private static final String KEY_SOFT_KEYBOARD_HEIGHT = "SoftKeyboardHeight";
    private SharedPreferences sharedPreferences;
    /**
     * 获取键盘的高度
     */
    private int getSoftKeyboardHeight() {
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //屏幕当前可见高度，不包括状态栏
        int displayHeight = rect.bottom - rect.top;
        //屏幕可用高度
        int availableHeight = ScreenUtils.getAvailableScreenHeight(activity);
        //用于计算键盘高度
        int softInputHeight = availableHeight - displayHeight - ScreenUtils.getStatusHeight(activity);
        Log.e("TAG-di", displayHeight + "");
        Log.e("TAG-av", availableHeight + "");
        Log.e("TAG-so", softInputHeight + "");
        if (softInputHeight != 0) {
            // 因为考虑到用户可能会主动调整键盘高度，所以只能是每次获取到键盘高度时都将其存储起来
            sharedPreferences.edit().putInt(KEY_SOFT_KEYBOARD_HEIGHT, softInputHeight).apply();
        }
        return softInputHeight;
    }
    /**
     * @param rootView
     * @return b
     * 判断键盘弹出状态
     */
    private boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }


    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emojiKeyboard.interceptBackPress()) {
            super.onBackPressed();
        }

    }
   /* @Override
    public void onBackPressed() {
    }*/


   /* @Override
    protected void onPause() {
        super.onPause();
        hideKeyboard(this);
        flEmogi.setVisibility(View.GONE);
        // ll_emogi.setVisibility(View.GONE);
    }*/


    /* */
    /**
    * @method
    * @description 隐藏键盘
    * @date: 2018/11/27 18:00
    * @author: ljp
    * @return
    */
    private void hideKeyboard(Activity context) {
        if (context == null) return;
        final View v = context.getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaUtil != null){
            mediaUtil.stop();
            mediaUtil = null;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * @descrption 分享开始的回调
     * @param platform 平台类型
     */
    @Override
    public void onStart(SHARE_MEDIA platform) {
    }
    /**
     * @descrption 分享成功的回调
     * @param platform 平台类型
     */
    @Override
    public void onResult(SHARE_MEDIA platform) {
        Toast.makeText(activity,"分享成功",Toast.LENGTH_LONG).show();
    }
    /**
     * @descrption 分享失败的回调
     * @param platform 平台类型
     * @param t 错误原因
     */
    @Override
    public void onError(SHARE_MEDIA platform, Throwable t) {
        Toast.makeText(activity,"分享失败"+t.getMessage(),Toast.LENGTH_LONG).show();
    }
    /**
     * @descrption 分享取消的回调
     * @param platform 平台类型
     */
    @Override
    public void onCancel(SHARE_MEDIA platform) {
        Toast.makeText(activity,"分享取消了",Toast.LENGTH_LONG).show();
    }
}
